if(NOT DEFINED _CMAKE_PROCESSING_LANGUAGE OR _CMAKE_PROCESSING_LANGUAGE STREQUAL "")
  message(FATAL_ERROR "Internal error: _CMAKE_PROCESSING_LANGUAGE is not set")
endif()

if(SEGGER_TOOLCHAIN_PKG_ROOT)
  string(TOLOWER ${CMAKE_SYSTEM_PROCESSOR} _cmake_sysproc)
  string(REGEX MATCH "^([^-]+)" _sysproc "${_cmake_sysproc}")  # use the first word that gets followed by a "-" as the actual processor name.
  file(GLOB _archdirs RELATIVE ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/*)
  set(_list "")
  foreach(_archdir ${_archdirs})
    if(IS_DIRECTORY ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/${_archdir})
      string(FIND ${_archdir} ${_sysproc} _pos)
      if(${_pos} EQUAL 0)
        set(_triple ${_archdir})
        break()
      endif()
    endif()
  endforeach()
  if(CMAKE_HOST_WIN32)
    set(_suffix ".exe")
  else()
    set(_suffix "")
  endif()
  if (_triple)
    message(STATUS "Found binutils: ${_triple}")
    find_program(CMAKE_AR 
      NAMES ar ar${_suffix}
      HINTS ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/${_triple}/bin NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
    )
    find_program(CMAKE_RANLIB 
      NAMES ranlib ranlib${_suffix}
      HINTS ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/${_triple}/bin NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
    )
    find_program(CMAKE_STRIP 
      NAMES strip strip${_suffix}
      HINTS ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/${_triple}/bin NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
    )
    find_program(CMAKE_NM 
      NAMES nm nm${_suffix}
      HINTS ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/${_triple}/bin NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
    )
    find_program(CMAKE_OBJCOPY 
      NAMES objcopy objcopy${_suffix}
      HINTS ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/${_triple}/bin NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
    )
    find_program(CMAKE_OBJDUMP 
      NAMES objdump objdump${_suffix}
      HINTS ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/${_triple}/bin NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
    )
  else()
    message(FATAL_ERROR "No binutils found. No architecture folder corresponding to ${_sysproc} under ${SEGGER_TOOLCHAIN_PKG_ROOT}/gcc/")
  endif()
else()
  message(FATAL_ERROR "No binutils found. SEGGER_TOOLCHAIN_PKG_ROOT was not set.")
endif()
